package org.hiucung.hlsdownloader.ui.components

import android.content.Context
import android.content.Intent
import android.widget.Toast
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.unit.dp
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import org.hiucung.hlsdownloader.FullScreenPlayerActivity
import org.hiucung.hlsdownloader.bean.M3U8TaskItem
import org.hiucung.hlsdownloader.bean.M3U8TaskState
import org.hiucung.hlsdownloader.bean.M3UPlaylist

/**
 * @title: DownloadListItem
 * @projectName HLS Downloader
 * @description: m3u8下载列表页面
 * @author Kicc
 * @date 2025/9/4 0:18
 */
@Composable
fun DownloadList(items: List<M3U8TaskItem>) {
    LazyColumn(
        modifier = Modifier.fillMaxSize(),
        verticalArrangement = Arrangement.spacedBy(8.dp)
    ) {
        items(items) { item ->
            DownloadListItem(item = item)
        }
    }
}


@Composable
fun DownloadListItem(item: M3U8TaskItem,context: Context = LocalContext.current) {

    var showDialog by remember { mutableStateOf(false) }

    var showDetailsDialog by remember { mutableStateOf(false) }

    var playlist by remember { mutableStateOf<M3UPlaylist?>(null) }

    if (showDetailsDialog) {
        // 异步加载 playlist
        LaunchedEffect(item.url) {
            withContext(Dispatchers.IO) {

                // TODO 展示 M38U列表信息

            }
        }

        BottomSheetDialog({ showDetailsDialog = false }) {
            Text(
                modifier = Modifier.padding(16.dp),
                text = playlist.toString(),
                style = MaterialTheme.typography.titleMedium
            )
        }
    }

    if (showDialog) {
        BottomSheetDialog({ showDialog = false }) {
            Column(
                modifier = Modifier.padding(16.dp)
            ) {
                Card(
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(horizontal = 16.dp, vertical = 4.dp),
                    elevation = CardDefaults.cardElevation(),
                    onClick = {
                        // viewmodel.delete
                    }
                ) {
                    Text(
                        modifier = Modifier.padding(16.dp),
                        text = "删除任务",
                        style = MaterialTheme.typography.titleMedium
                    )
                }

                Card(
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(horizontal = 16.dp, vertical = 4.dp),
                    elevation = CardDefaults.cardElevation(),
                    onClick = {
                        if (item.status is M3U8TaskState.MergeCompleted) {
                            // 启动全屏播放Activity
                            val intent = Intent(context, FullScreenPlayerActivity::class.java).apply {
                                putExtra("VIDEO_PATH", item.outputPath.toString())
                            }
                            context.startActivity(intent)
                            showDialog = false
                        } else {
                            Toast.makeText(context, "视频未合并", Toast.LENGTH_SHORT).show()
                        }
                    }
                ) {
                    Text(
                        modifier = Modifier.padding(16.dp),
                        text = "播放视频（本地）",
                        style = MaterialTheme.typography.titleMedium
                    )
                }

                Card(
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(horizontal = 16.dp, vertical = 4.dp),
                    elevation = CardDefaults.cardElevation(),
                    onClick = {
                        showDialog =false
                        showDetailsDialog = true
                    }
                ) {
                    Text(
                        modifier = Modifier.padding(16.dp),
                        text = "详细信息",
                        style = MaterialTheme.typography.titleMedium
                    )
                }
            }
        }
    }

    Card(
        modifier = Modifier
            .fillMaxWidth()
            .padding(horizontal = 16.dp, vertical = 4.dp),
        elevation = CardDefaults.cardElevation(),
        onClick = {
            showDialog = true
        }
    ) {
        Column(
            modifier = Modifier.padding(16.dp)
        ) {
            Text(
                text = item.name,
                style = MaterialTheme.typography.titleMedium
            )
            Text(
                text = item.url,
                style = MaterialTheme.typography.bodySmall,
                color = MaterialTheme.colorScheme.onSurfaceVariant,
                maxLines = 1,
                modifier = Modifier.padding(top = 4.dp)
            )

            Row(modifier = Modifier.fillMaxWidth()) {
                Text(
                    text = when (item.status) {
                        is M3U8TaskState.WaitingDownload -> "等待下载"
                        is M3U8TaskState.Downloading -> "正在下载"
                        is M3U8TaskState.DownloadCompleted -> "下载完成"
                        is M3U8TaskState.WaitingMerge -> "等待合并"
                        is M3U8TaskState.Merging -> "正在合并"
                        is M3U8TaskState.MergeCompleted -> "合并完成"
                        is M3U8TaskState.Error -> "下载失败"
                    },
                    style = MaterialTheme.typography.labelMedium,
                    color = when (item.status) {
                        M3U8TaskState.WaitingDownload -> MaterialTheme.colorScheme.onSurfaceVariant
                        is M3U8TaskState.MergeCompleted -> MaterialTheme.colorScheme.primary
                        is M3U8TaskState.Error -> MaterialTheme.colorScheme.error
                        else -> MaterialTheme.colorScheme.onSurfaceVariant
                    },
                    modifier = Modifier
                        .padding(top = 8.dp)
                        .weight(1f)
                )

                if (item.status is M3U8TaskState.Downloading || item.status is M3U8TaskState.Merging) {
                    Text(
                        text = "${item.downloadedSegments}/${item.totalSegments}",
                        style = MaterialTheme.typography.labelSmall,
                        modifier = Modifier.padding(top = 8.dp)
                    )
                }
            }
        }
    }
}